package com.hzzftech.watchdog.busi.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.hzzftech.watchdog.busi.constants.BusiConstant;
import com.hzzftech.watchdog.busi.core.executor.JobExecutor;
import com.hzzftech.watchdog.busi.core.executor.TransExecutor;
import com.hzzftech.watchdog.busi.core.executor.starter.KettleEnvironmentStarter;
import com.hzzftech.watchdog.busi.core.util.KettleThreadPool;
import com.hzzftech.watchdog.busi.domain.KtDispatcher;
import com.hzzftech.watchdog.busi.domain.KtParams;
import com.hzzftech.watchdog.busi.domain.RJob;
import com.hzzftech.watchdog.busi.encrypt.DESEncrypt;
import com.hzzftech.watchdog.busi.service.IKtDispatcherService;
import com.hzzftech.watchdog.busi.service.IKtParamsService;
import com.hzzftech.watchdog.busi.service.IKtRepositoryNodeService;
import com.hzzftech.watchdog.busi.service.impl.KtDispatcherServiceImpl;
import com.hzzftech.watchdog.common.config.KtWatchdogConfig;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.repository.LongObjectId;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.pentaho.di.trans.TransMeta;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.hzzftech.watchdog.common.annotation.Log;
import com.hzzftech.watchdog.common.enums.BusinessType;
import com.hzzftech.watchdog.busi.domain.RTransformation;
import com.hzzftech.watchdog.busi.service.IRTransformationService;
import com.hzzftech.watchdog.common.core.controller.BaseController;
import com.hzzftech.watchdog.common.core.domain.AjaxResult;
import com.hzzftech.watchdog.common.utils.poi.ExcelUtil;
import com.hzzftech.watchdog.common.core.page.TableDataInfo;

/**
 * 数据库资源库_transController
 * 
 * @author kt-watchdog
 * @date 2022-01-27
 */
@Controller
@RequestMapping("/busi/TRANSFORMATION")
public class RTransformationController extends BaseController
{
    private String prefix = "busi/TRANSFORMATION";

    @Autowired
    private IRTransformationService rTransformationService;

    @Autowired
    private KtDispatcherServiceImpl ktDispatcherService;

    @Autowired
    private IKtParamsService iKtParamsService;

    @Autowired
    private IKtRepositoryNodeService nodeService;

    @Value("${kt-watchdog.DES_SECURITY_KEY}")
    private String desSecurityKey;

    @RequiresPermissions("busi:TRANSFORMATION:view")
    @GetMapping()
    public String TRANSFORMATION()
    {
        return prefix + "/TRANSFORMATION";
    }

    @RequiresPermissions("busi:TRANSFORMATION:view")
    @GetMapping("/select")
    public String TRANSFORMATIONSelect()
    {
        return prefix + "/TRANSFORMATIONSelect";
    }

    /**
     * 查询数据库资源库_trans列表
     */
    @RequiresPermissions("busi:TRANSFORMATION:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(RTransformation rTransformation)
    {
        KettleDatabaseRepository repository = (KettleDatabaseRepository) KettleEnvironmentStarter.instance.getRepository();
        startPage();
        List<RTransformation> list = rTransformationService.selectRTransformationList(rTransformation);
        try {
            for (RTransformation t : list) {
                t.setDirectoryPath(repository.findDirectory(new LongObjectId(t.getIdTransformation())).getPath());
            }
        } catch (Exception e) {
            logger.error("");
            return getDataTable(new ArrayList<>());
        }
        return getDataTable(list);
    }
    /**
     * 删除数据库资源库_trans
     */
    @RequiresPermissions("busi:TRANSFORMATION:remove")
    @Log(title = "数据库资源库_trans", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        KettleDatabaseRepository repository = (KettleDatabaseRepository) KettleEnvironmentStarter.instance.getRepository();
        int delCount = 0;
        try {
            for (String id : ids.split(",")) {
                repository.deleteTransformation(new LongObjectId(Long.parseLong(id)));
                delCount ++;
            }
        } catch (Exception e) {
            logger.error("删除失败", e);
        }
        return toAjax(delCount);
    }

    /**
     * 导出 JOB xml
     */
    @RequiresPermissions("busi:JOB:export")
    @Log(title = "kettle运行提醒信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(RTransformation trans)
    {
        KettleDatabaseRepository repository = (KettleDatabaseRepository) KettleEnvironmentStarter.instance.getRepository();
        FileOutputStream out = null;
        try {
            TransMeta transMeta = repository.loadTransformation(new LongObjectId(trans.getIdTransformation()), "");
            String xml = transMeta.getXML();
            String fileName = transMeta.getName()+".ktr";
            String downloadPath = KtWatchdogConfig.getDownloadPath() +fileName;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
            out = new FileOutputStream(downloadPath);
            out.write(xml.getBytes());

            return AjaxResult.success(fileName);
        } catch (Exception e) {
            logger.error("导出JOB异常", e);
            return AjaxResult.error();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("导出JOB异常", e);
                }
            }
        }
    }

}
